<?php
namespace app\common\service;

use app\common\helper\WeixinHelper;
use app\common\util\Util;
use think\Model;

class WxTplMsgService extends BaseService
{

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 发送模版消息
     * @param $sid 店铺Id
     * @param $id 用于查询相应类型数据的Id
     * @param $type 发送类型
     * @param array $data 其他参数
     */
    public function send($sid, $id, $type, $data = [])
    {
        if (empty($id) || empty($type)) {
            $this->addLog(['result_msg' => '参数错误', 'sid' => $sid]);
        }

        switch ($type) {
            // 新用户上级提醒
            case 'user':
                //$id为客户Id
                return $this->sendNewUserMsg($sid, $id);
                break;

            //试听课审核通过提醒
            case 'course_packet':
                //$id为course_listening试听审核的id
                return $this->sendCoursePacketMsg($sid, $id);
                break;

            // 课程开课提醒
            case 'course_begin':
                //$id为课程id,data为学员id数组
                return $this->sendCourseBeginMsg($sid, $id, $data);
                break;

            //拜访客户提醒
            case 'customer_visiting':
                //$id为拜访vid
                return $this->sendCustomerVisitingMsg($sid, $id);
                break;

            // 课程结束签到报表
            case 'course_sign':
                //$id为课程courseid
                return $this->sendCourseSignMsg($sid, $id);
                break;

            //月签到报表
            case 'month_sign':
                //$id为statis_month_sign表中的os_id
                return $this->sendMonthSignMsg($sid, $id);
                break;

            // 模版店铺新增班级
            case 'template_store_class':
                //$id为班级Id:classid
                return $this->sendTemplateStoreClassMsg($sid, $id);
                break;

            // 模版店铺新增课程
            case 'template_store_course':
                //$id为课程Id:courseid
                return $this->sendTemplateStoreCourseMsg($sid, $id);
                break;

            // 线下支付申请通知
            case 'offline_payment_apply':
                //$id为用户UID,$data为课程信息
                return $this->sendOfflinePaymentApplyMsg($sid, $id, $data);
                break;

            // 线下支付未通过提醒
            case 'offline_payment_refuse':
                //$id为用户UID,$data为课程信息
                return $this->sendOfflinePaymentRefuseMsg($sid, $id, $data);
                break;

            // 线下支付通过提醒
            case 'offline_payment_pass':
                //$id为用户UID,$data为课程信息
                return $this->sendOfflinePaymentPassMsg($sid, $id, $data);
                break;

            // 下单成功提醒
            case 'payment_success':
                //$id为用户UID,$data为订单信息(必须包含订单金额和课程ID)
                return $this->sendPaymentSuccessMsg($sid, $id, $data);
                break;

            // 签到成功提醒
            case 'sign_success':
                //$id为用户UID,$data为课程信息
                return $this->sendSignSuccessMsg($sid, $id, $data);
                break;

            // 优惠券赠送提醒
            case 'coupon_present':
                //$id为赠送对象UID
                return $this->sendCouponPresentMsg($sid, $id, $data);
                break;

            // 管理员邀请绑定
            case 'bind_manager':
                //$id为用户UID
                return $this->sendBindManagerMsg($sid, $id);
                break;
        }
        exit();
    }


    /**
     * 发送管理员邀请绑定消息
     * @param $sid
     * @param $uid
     * @return bool|int
     */
    public function sendBindManagerMsg($sid, $uid)
    {
        $wx_tpl = $this->getTplMsgSetting($sid, 37);
        if ($wx_tpl === false) {
            return false;
        }

        $open_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('touser');
        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 21, ['uid' => $uid]);


        $info['user_nickname'] = db('user')->where('user_id', $uid)->value('user_nickname');
        $info['apply_time'] = time();
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $info);

        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 发送优惠券赠送消息
     * @param $sid
     * @param $uid
     * @param array $coupon_info
     * @return bool|int
     */
    public function sendCouponPresentMsg($sid, $uid, $coupon_info = [])
    {
        $wx_tpl = $this->getTplMsgSetting($sid, 36);
        if ($wx_tpl === false) {
            return false;
        }

        $open_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('touser');

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 20, ['uid' => $uid]);

        $info['name'] = db('store')->where('store_id', $sid)->value('store_name');
        $info['coupon_begin'] = $coupon_info['coupon_begin'];
        $info['coupon_end'] = $coupon_info['coupon_end'];
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $info);

        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 签到成功提醒
     * @param $sid
     * @param $uid
     * @param array $course_info
     * @return bool|int
     */
    private function sendSignSuccessMsg($sid, $uid, $course_info = [])
    {
        $course_students = db('course_students')
            ->where([
                'sid' => $sid,
                'uid' => $uid,
                'courseid' => $course_info['courseid'],
                'sign_status' => 1
            ])
            ->find();
        if (!$course_students) {
            $this->addLog(['result_msg' => '非法签到', 'sid' => $sid]);
            return false;
        }

        $wx_tpl = $this->getTplMsgSetting($sid, 35);
        if ($wx_tpl === false) {
            return false;
        }
        $open_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('touser');

        $speaker = json_decode($course_info['speaker'], 1);
        $course_info['speaker'] = $speaker[0]['speaker_name'];
        $course_info['sign_time'] = time();
        $course_info['uid'] = $uid;
        $course_info['students_name'] = db('students')->where(['sid' => $sid, 'uid' => $uid])->value('name');

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 19, $course_info);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $course_info);
        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 下单成功提醒
     * @param $sid
     * @param $uid
     * @param array $order_info
     * @return bool|int
     */
    private function sendPaymentSuccessMsg($sid, $uid, $order_info = [])
    {
        //获取学员信息
        $students = db('students')->field('name,phone,company')->where(['sid' => $sid, 'uid' => $uid])->find();

        //查询上级顾问
        $pid = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_id');
        $where = [
            'sid' => $sid
        ];
        if ($pid) {
            //存在上级顾问
            $where['userid'] = $pid;
        } else {
            //不存在上级顾问，获取管理员信息
            $where['is_administrator'] = 1;
        }
        $user = db('user_integral')->field('userid,touser')->where($where)->find();
        $open_id = $user['touser'];

        if (!$open_id) {
            $this->addLog(['result_msg' => '上级顾问和管理员不存在', 'sid' => $sid]);
            return false;
        }

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 34);
        if ($wx_tpl === false) {
            return false;
        }
        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];

        $order_info['uid'] = $user['userid'];
        $order_info['students_name'] = $students['name'];
        $order_info['phone'] = $students['phone']; //
        $company = Util::unserializeStr($students['company']);
        $order_info['company'] = $company[0]['cname']; //公司信息

        //课程名称
        $order_info['name'] = db('course')->where(['courseid' => $order_info['course_id']])->value('name');

        $send_data['url'] = '';
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $order_info);
        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 线下支付课程审核通过提醒
     * @param $sid
     * @param $uid
     * @param array $course_info
     * @return bool|int
     */
    private function sendOfflinePaymentPassMsg($sid, $uid, $course_info = [])
    {
        return $this->sendOfflinePaymentOperateMsg($sid, $uid, $course_info, 33);
    }

    /**
     * 线下支付课程审核拒绝提醒
     * @param $sid
     * @param $uid
     * @param array $course_info
     * @return bool|int
     */
    private function sendOfflinePaymentRefuseMsg($sid, $uid, $course_info = [])
    {
        return $this->sendOfflinePaymentOperateMsg($sid, $uid, $course_info, 32);
    }

    private function sendOfflinePaymentOperateMsg($sid, $uid, $course_info = [], $business_no)
    {
        $open_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('touser');

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, $business_no);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];
        $course_info['uid'] = $uid;
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 18, $course_info);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $course_info);
        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 发送线下支付申请模版消息
     * @param $sid
     * @param $uid
     * @param array $course_info
     * @return bool
     */
    private function sendOfflinePaymentApplyMsg($sid, $uid, $course_info = [])
    {
        //获取学员信息
        $students = db('students')->field('name,phone')->where(['sid' => $sid, 'uid' => $uid])->find();

        //查询上级顾问
        $pid = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_id');
        $where = [
            'sid' => $sid
        ];
        if ($pid) {
            //存在上级顾问
            $where['userid'] = $pid;
        } else {
            //不存在上级顾问，获取管理员信息
            $where['is_administrator'] = 1;
        }
        $user = db('user_integral')->field('userid,touser')->where($where)->find();
        $open_id = $user['touser'];

        if (!$open_id) {
            $this->addLog(['result_msg' => '上级顾问和管理员不存在', 'sid' => $sid]);
            return false;
        }

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 31);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];

        $course_info['uid'] = $user['userid'];
        $course_info['students_name'] = $students['name'];
        $course_info['phone'] = $students['phone'];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 17, $course_info);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $course_info);
        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 每月一号，给管理层发送月签到报表
     * @param $sid
     * @param $os_id
     * @return bool
     */
    private function sendMonthSignMsg($sid, $os_month)
    {
        //月报表详情
        $info = db('statis_month_sign')->where(['os_month' => $os_month, 'sid' => $sid])->find();
        if (empty($info)) {
            $this->addLog(['result_msg' => '月报表不存在', 'uid' => '', 'sid' => $sid]);
            return false;
        }

        $wx_tpl = $this->getTplMsgSetting($sid, 27);

        if ($wx_tpl === false) {
            $this->addLog(['result_msg' => '模版不存在或已关闭', 'uid' => '', 'sid' => $sid]);
            return false;
        }
        if (empty($wx_tpl['receive_uids'])) {
            $this->addLog(['result_msg' => '每月一号，给管理层发送月签到报表，没有发送对象', 'uid' => '', 'sid' => $sid]);
            return false;
        }
        $uids = unserialize($wx_tpl['receive_uids']);
        //获取touser
        $users = db('user_integral')->field('touser,userid')->whereIn('userid', $uids)->select();
        if (!empty($users)) {
            foreach ($users as $v) {
                $send_data = [];
                $send_data['touser'] = $v['touser'];
                $send_data['template_id'] = $wx_tpl['template_no'];
                $url_data = [
                    'uid' => $v['userid'],
                    'os_id' => $info['os_id']
                ];
                $send_data['url'] = $this->getTemplateLinkUrl($sid, 13, $url_data);
                $data = [
                    'sign_name' => '月度报表（' . $info['os_month'] . '）',
                    'course_num' => $info['course_num'],
                    'sign_num' => $info['sign_ourclass_num'] + $info['sign_apply_num'],
                    'signed_num' => $info['signed_ourclass_num'] + $info['signed_other_num'],
                    'formal_num' => $info['signed_ourclass_num'],
                ];
                $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $data);
                $result = WeixinHelper::sendTemplateMsg($sid, $send_data);
                $res = json_decode($result, 1);
            }
        }


        return $res['errcode'] != 0 ? false : true;

    }

    /**
     * 课程结束，给管理层发送签到报表
     * @param $sid
     * @param $courseid
     * @return bool
     */
    private function sendCourseSignMsg($sid, $courseid)
    {
        //课程详情
        $info = db('course')->where(['courseid' => $courseid])->find();
        if (empty($info)) {
            $this->addLog(['result_msg' => '课程不存在', 'uid' => '', 'sid' => $sid]);
            return false;
        }
        $courseServer = new CourseService();
        $sign_ourclass_num = $courseServer->getFormalStudentsCountByCourseid($courseid);
        $sign_other_num = $courseServer->getPassUserCountByCourseid($courseid);
        $sign_num = $sign_ourclass_num + $sign_other_num;
        $signed_num = $courseServer->getSignedCountByCourseid($courseid);
        $formal_num = $courseServer->getSignedFormalStudentsCountByCourseid($courseid);
        $other_num = $signed_num - $formal_num;
        //存入statis_course_sign
        $insert_data = [
            'os_month' => date('Ym', time()),
            'sid' => $sid,
            'courseid' => $courseid,
            'sign_ourclass_num' => $sign_ourclass_num,
            'sign_apply_num' => $sign_other_num,
            'signed_ourclass_num' => $formal_num,
            'signed_other_num' => $other_num,
            'addtime' => time()
        ];
        db('statis_course_sign')->insert($insert_data);
        $wx_tpl = $this->getTplMsgSetting($sid, 26);

        if ($wx_tpl === false) {
            $this->addLog(['result_msg' => '模版不存在或已关闭', 'uid' => '', 'sid' => $sid]);
            return false;
        }
        if (empty($wx_tpl['receive_uids'])) {
//            $this->addLog(['result_msg'=>'课程结束，给管理层发送签到报表，没有发送对象','uid' => '', 'sid' => $sid]);
            return false;
        }
        $uids = unserialize($wx_tpl['receive_uids']);
        //获取touser
        $users = db('user_integral')->field('touser,userid')->whereIn('userid', $uids)->select();
        if (!empty($users)) {
            foreach ($users as $v) {
                $send_data = [];
                $send_data['touser'] = $v['touser'];
                $send_data['template_id'] = $wx_tpl['template_no'];
                $url_data = [
                    'uid' => $v['userid'],
                    'courseid' => $courseid
                ];
                $send_data['url'] = $this->getTemplateLinkUrl($sid, 12, $url_data);
                $data = [
                    'name' => $info['name'],
                    'sign_num' => $sign_num,
                    'signed_num' => $signed_num,
                    'formal_num' => $formal_num,
                    'other_num' => $other_num,
                ];
                $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $data);
                $result = WeixinHelper::sendTemplateMsg($sid, $send_data);
                $res = json_decode($result, 1);
            }
        }


        return $res['errcode'] != 0 ? false : true;

    }

    /**
     * 给顾问发送拜访客户提醒
     * @param $sid
     * @param $uid
     * @return bool
     */
    private function sendCustomerVisitingMsg($sid, $vid)
    {
        //拜访记录
        $info = db('visiting')->where(['vid' => $vid])->find();
        //获取客户姓名
        $customer_name = db('students')->where(['uid' => $info['uid'], 'sid' => $sid])->value('name');
        //获取顾问信息
        $counselor_info = db('user u')
            ->field('u.user_id,u.user_nickname,ui.touser')
            ->join('user_integral ui', 'u.user_id=ui.userid', 'LEFT')
            ->where(['ui.sid' => $sid, 'u.user_id' => $info['create_uid']])
            ->find();


        if (!empty($counselor_info) && $counselor_info['touser']) {
            $wx_tpl = $this->getTplMsgSetting($sid, 25);
            if ($wx_tpl === false) {
                return false;
            }

            $send_data = [];
            $send_data['touser'] = $counselor_info['touser'];
            $send_data['template_id'] = $wx_tpl['template_no'];
            $send_data['url'] = '';
            $data = [
                'customer_name' => $customer_name,
                'counselor_name' => $counselor_info['user_nickname'],
                'next_time' => $info['next_time']
            ];
            $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $data);
            $result = WeixinHelper::sendTemplateMsg($sid, $send_data);
            $res = json_decode($result, 1);

            return $res['errcode'] != 0 ? false : true;
        } else {
            $this->addLog(['result_msg' => '模版不存在或已关闭', 'uid' => $info['create_uid'], 'sid' => $sid]);
            return false;
        }
    }

    /**
     * 给上级发送新用户模版消息
     * @param $sid
     * @param $uid
     * @return bool
     */
    private function sendNewUserMsg($sid, $uid)
    {
        $info = db('user u')
            ->field('u.user_id,u.user_nickname,u.user_mobile,u.create_time,ui.parent_id,ui.touser')
            ->join('user_integral ui', 'u.user_id=ui.userid', 'LEFT')
            ->where(['ui.sid' => $sid, 'u.user_id' => $uid])
            ->find();

        //获取上级信息
        $parent_info = db('user_integral')->field('touser,userid')->where(['sid' => $sid, 'userid' => $info['parent_id']])->find();

        if (!empty($parent_info) && $parent_info['touser']) {
            $wx_tpl = $this->getTplMsgSetting($sid, 15);
            if ($wx_tpl === false) {
                return false;
            }

            $send_data = [];
            $send_data['touser'] = $parent_info['touser'];
            $send_data['template_id'] = $wx_tpl['template_no'];
            $data = [
                'cid' => $uid,
                'uid' => $parent_info['userid']
            ];
            $send_data['url'] = $this->getTemplateLinkUrl($sid, 11, $data);
            $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $info);

            $result = WeixinHelper::sendTemplateMsg($sid, $send_data);
            $res = json_decode($result, 1);

            return $res['errcode'] != 0 ? false : true;
        } else {
            $this->addLog(['result_msg' => '模版不存在或已关闭', 'uid' => $parent_info['userid'], 'sid' => $sid]);
            return false;
        }
    }

    /**
     * 课程开课提醒
     * @param $sid
     * @param $course_id
     * @param array $open_ids
     * @return bool
     */
    private function sendCourseBeginMsg($sid, $course_id, $open_ids = [])
    {
        $info = db('course')->field('name,speaker,schooltime,courseid')->where(['courseid' => $course_id])->find();
        if (empty($info)) {
            $this->addLog(['result_msg' => '课程记录不存在', 'sid' => $sid]);
            return false;
        }
        $speaker = json_decode($info['speaker'], 1);
        $info['speaker'] = $speaker[0]['speaker_name'];

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 22);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $flag = true;
        foreach ($open_ids as $v) {
            $send_data['touser'] = $v;
            $send_data['template_id'] = $wx_tpl['template_no'];
            $cid = db('user_integral')->where(['touser' => $v, 'sid' => $sid])->value('userid');
            $data = [
                'cid' => $cid,
                'courseid' => $course_id
            ];
            $send_data['url'] = $this->getTemplateLinkUrl($sid, 10, $data);
            $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $info);

            $result = WeixinHelper::sendTemplateMsg($sid, $send_data);
            $res = json_decode($result, 1);
            if ($res['errcode'] != 0) {
                $flag = false;
            }
        }
        return $flag;
    }

    public function send_template_msg($sid, $data = [])
    {
        $access_token = WeixinHelper::get_wechat($sid)->access_token->getTokenFromServer();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token['access_token'];
        $res = $this->http_request($url, $data);
        return json_decode($res, true);
    }

    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
//        curl_close($curl);
        if ($output) {
            curl_close($curl);
            return $output;
        } else {
            $error = curl_errno($curl);
            curl_close($curl);
            return $error;
        }
//        return $output;
    }

    /**
     * 发送试听课程审核成功消息模版
     * @param $sid
     * @param $course_listening_id
     * @return bool
     */
    private function sendCoursePacketMsg($sid, $course_listening_id)
    {
        //获取试听详情
        $info = db()->name('course_listening cl')
            ->field('cl.*,c.name,c.speaker,c.schooltime,u.user_openid')
            ->join('user u', 'cl.uid = u.user_id')
            ->join('course c', 'cl.courseid = c.courseid', 'LEFT')
            ->where(['cl.id' => $course_listening_id])
            ->find();
        if (empty($info)) {
            $this->addLog(['result_msg' => '课程试听申请记录不存在', 'sid' => $sid]);
            return false;
        }

        $speaker = json_decode($info['speaker'], 1);
        $info['speaker'] = $speaker[0]['speaker_name'];

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 21);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $send_data['touser'] = $info['user_openid'];
        $send_data['template_id'] = $wx_tpl['template_no'];
        $data = [
            'cid' => $info['uid'],
            'courseid' => $info['courseid']
        ];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 9, $data);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $info);

        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }

    /**
     * 发送模版店铺新增班级消息模版
     * @param $sid
     * @param $class_id
     * @return bool
     */
    private function sendTemplateStoreClassMsg($sid, $class_id)
    {
        $class_info = db('classes')->where(['classid' => $class_id, 'status' => ['<>', -1]])->find();
        if (!$class_info) {
            $this->addLog(['result_msg' => '班级信息不存在', 'sid' => $sid]);
            return false;
        }

        //学校名称
        $class_info['store_name'] = db('store')->where(['store_id' => $sid])->value('store_name');
        //学期
        $class_info['term'] = date('Y', time());
        //科目
        $class_info['subject'] = '全部';
        //节次
        $class_info['class_num'] = 40;

        //获取店铺管理员信息
        $user = db('user_integral')->field('userid,touser')->where(['sid' => $sid, 'is_administrator' => 1])->find();
        $open_id = $user['touser'];
        if (!$open_id) {
            $this->addLog(['result_msg' => '管理员不存在', 'sid' => $sid]);
            return false;
        }
        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 29);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];

        $class_info['uid'] = $user['userid'];
        $send_data['url'] = $this->getTemplateLinkUrl($sid, 15, $class_info);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $class_info);

        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }


    /**
     * 发送模版店铺新增课程消息模板
     * @param $sid
     * @param $course_id
     * @return bool
     */
    private function sendTemplateStoreCourseMsg($sid, $course_id)
    {
        $course_info = db('course')->where(['courseid' => $course_id])->find();
        if (!$course_info) {
            $this->addLog(['result_msg' => '课程信息不存在', 'sid' => $sid]);
            return false;
        }

        $user = db('user_integral')->field('userid,touser')->where(['sid' => $sid, 'is_administrator' => 1])->find();
        $open_id = $user['touser'];
        if (!$open_id) {
            $this->addLog(['result_msg' => '管理员不存在', 'sid' => $sid]);
            return false;
        }

        $course_info['course_status'] = '未开课';
        $course_info['course_progress'] = '预告';
        $course_info['uid'] = $user['userid'];

        //判断模版消息配置是否成功
        $wx_tpl = $this->getTplMsgSetting($sid, 30);
        if ($wx_tpl === false) {
            return false;
        }

        $send_data = [];
        $send_data['touser'] = $open_id;
        $send_data['template_id'] = $wx_tpl['template_no'];

        $send_data['url'] = $this->getTemplateLinkUrl($sid, 16, $course_info);
        $send_data['data'] = $this->parseTemplateCfg($wx_tpl, $course_info);

        return WeixinHelper::sendTemplateMsg($sid, $send_data);
    }


    /**
     * 消息模版链接地址
     * @param $sid
     * @param $type
     * @param $data
     * @return string
     */
    public function getTemplateLinkUrl($sid, $type, $data = [])
    {
        $domain = db('store')->where(['store_id' => $sid])->value('domain');
        $host = $domain == '' ? $_SERVER['HTTP_HOST'] : $domain;
        $host = Util::http_url_path($host);
        $link = '';
        switch ($type) {
            //微官网
            case 3:
                $link = $host . '/index.html';
                break;
            //课程详情页面
            case 9:
                $link = $host . '/m/html/dmsedu.html?sid=' . $sid . '&uid=' . $data['cid'] . '&escape=detail.' . $data['courseid'];
                break;
            //上课确认页面
            case 10:
//                $link = $host.'/m/html/dmsedu.html?type=3&sid='.$sid.'&uid='.$data['cid'].'&escape=detail.'.$data['courseid'];
                $link = $host . '/m/html/dmsedu.html?&sid=' . $sid . '&uid=' . $data['cid'] . '&escape=detail.' . $data['courseid'] . '.3';
                break;
            //完善粉丝资料
            case 11:
                $link = $host . '/m/html/customs/sid/' . $sid . '/uid/' . $data['uid'] . '/cid/' . $data['cid'];
                break;
            //每节课报表
            case 12:
                $link = $host . '/m/html/dmshelper.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=statis.bone.' . $data['courseid'];
                break;
            //月报表
            case 13:
                $link = $host . '/m/html/dmshelper.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=statis.bmore.' . $data['os_id'];
                break;
            //模版店铺新增班级
            case 15:
                $link = $host . '/m/html/dmscommon.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=synclass.' . $data['classid'];
                break;
            //模版店铺新增课程
            case 16:
                $link = $host . '/m/html/dmscommon.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=syncourse.' . $data['courseid'];
                break;
            //线下支付申请页面
            case 17:
                $link = $host . '/m/html/dmscommon.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=orderConfirm.' . $data['order_id'];
                break;
            //我的订单页面
            case 18:
                $link = $host . '/m/html/dmsedu.html?sid=' . $sid . '&uid=' . $data['uid'] . '&escape=order';
                break;
            //签到成功，听课证页面
            case 19:
//                $link = $host . '/m/html/dmsedu.html?sid=' . $sid . '&escape=signSuccess.' . $data['courseid'];
                $link = $host . '/m/html/dmscommon.html?sid=' . $sid . '&escape=signSuccess.' . $data['courseid'];
                break;
            // 我的优惠券
            case 20:
                $link = $host . '/m/html/dmsedu.html?sid=' . $sid . '&uid='.$data['uid'] . '&escape=coupon';
                break;
            // 管理员申请页面(邀请绑定)
            case 21:
                $link = $host . '/m/bind_manager/confirm?sid=' . $sid . '&uid='.$data['uid'];
                break;
        }
        return $link;
    }

    /**
     * 解析模版配置参数
     * @param $template
     * @param array $data
     * @return mixed
     */
    public function parseTemplateCfg($template, $data = [], $type = 1)
    {
        $config = json_decode($template['template_config'], 1);
        foreach ($config as $ck => $cv) {
            if ($type == 1) {
                $parse_data[str_replace('.DATA', '', $cv['name'])] = [
                    '0' => $this->parseTemplateCfgContent($cv['value'], $cv['custom_value'], $data),
                    '1' => $cv['color']
                ];
            } else {
                $parse_data[str_replace('.DATA', '', $cv['name'])] = [
                    'value' => $this->parseTemplateCfgContent($cv['value'], $cv['custom_value'], $data),
                    'color' => $cv['color']
                ];
            }
        }
        return $parse_data;
    }


    /**
     * 根据模版配置，解析配置内容
     * @param $type
     * @param string $custom
     * @param array $data
     */
    public function parseTemplateCfgContent($type, $custom = '', $data = [])
    {
        $value = '';
        switch ($type) {
            case 0:
                $value = $custom;
                break;
            case 18:
                //会员联系方式
                $value = $data['user_mobile'] ? $data['user_mobile'] : '暂无';
                break;
            case 25:
                //会员昵称
                $value = $data['user_nickname'];
                break;
            case 26:
                //会员加入时间
                $value = date("Y-m-d H:i:s", $data['create_time']);
                break;
            case 37:
                //课程名称
                $value = $data['name'];
                break;
            case 38:
                //课程开始时间
                $value = date("Y-m-d H:i:s", $data['schooltime']);
                break;
            case 39:
                //教师
                $value = $data['speaker'];
                break;
            case 41:
                //拜访客户姓名
                $value = $data['customer_name'];
                break;
            case 42:
                //顾问姓名
                $value = $data['counselor_name'] . '(微信昵称)';
                break;
            case 43:
                //拜访开始时间
                $value = date("Y-m-d H:i:s", $data['next_time']);
                break;
            case 44:
                //应签人数
                $value = $data['sign_num'];
                break;
            case 45:
                //实签人数
                $value = $data['signed_num'];
                break;
            case 46:
                //正式学员人数
                $value = $data['formal_num'];
                break;
            case 47:
                //旁听人数
                $value = $data['other_num'];
                break;
            case 48:
                //课程数
                $value = $data['course_num'];
                break;
            case 49:
                //月报表名称
                $value = $data['sign_name'];
                break;
            case 54:
                //班级名称
                $value = $data['name'];
                break;
            case 55:
                $value = $custom;
                break;
            case 56:
                //学校名称
                $value = $data['store_name'];
                break;
            case 57:
                //学期
                $value = $data['term'];
                break;
            case 58:
                //科目
                $value = $data['subject'];
                break;
            case 59:
                //节次
                $value = $data['class_num'];
                break;
            case 60:
                //新增课程
                $value = $custom;
                break;
            case 61:
                //课程状态
                $value = $data['course_status'];
                break;
            case 62:
                //课程进度
                $value = $data['course_progress'];
                break;
            case 63:
                //学员姓名
                $value = $data['students_name'];
                break;
            case 64:
                //学员联系方式
                $value = $data['phone'];
                break;
            case 65:
                //学员公司信息
                $value = $data['company'];
                break;
            case 66:
                //订单金额
                $value = $data['order_amount'];
                break;
            case 67:
                //签到时间
                $value = date('Y-m-d H:i:s', $data['sign_time']);
                break;
            case 68:
                $begin_time = date('Y-m-d', $data['coupon_begin']);
                $end_time = date('Y-m-d', $data['coupon_end']);
                $value = '有效期('.$begin_time.'至'.$end_time.')';
                break;
            case 69:
                $value = date("Y-m-d H:i:s", $data['apply_time']);
                break;
        }
        return $value;
    }

    /**
     * @param $sid
     * @param $bussiness_no
     * @param int $uid
     * @return bool
     */
    private function getTplMsgSetting($sid, $bussiness_no, $uid = 0)
    {
        $tpl_setting = db('msg_setting')->where(['sid' => $sid, 'bussiness_no' => $bussiness_no])->find();
        if (empty($tpl_setting)) {
            $this->addLog(['result_msg' => '模版不存在', 'sid' => $sid, 'uid' => $uid]);
            return false;
        } else {
            if ($tpl_setting['wx_status'] == 0) {
                $this->addLog(['result_msg' => '模版已关闭', 'sid' => $sid]);
                return false;
            }
            $wx_tpl = db('wx_template')->where(['sid' => $sid, 'template_type' => $tpl_setting['wx_template_type']])->find();
            $wx_tpl['receive_uids'] = $tpl_setting['receive_uids'];
            if (empty($wx_tpl)) {
                $this->addLog(['result_msg' => '未配置模版消息', 'sid' => $sid]);
                return false;
            }
        }
        return $wx_tpl;
    }

    private function addLog($data)
    {
        $data['uid'] = 0;
        $data['touser'] = '';
        $data['send_status'] = 1;
        $data['add_time'] = time();
        $data['send_time'] = time();
        db('wx_msg_log')->insert($data);
    }

}







